package com.le.tester.tip;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * createTime：2023/5/11 10:25
 * description：buffer中的position limit capacity
 * 基于三次copy的原理，演变而成的代码模板,read write
 */
@Slf4j
public class BufferDemo {
    public static void main(String[] args) throws IOException {

        try (FileInputStream fileStream = new FileInputStream("E:\\Desktop\\新建文本文档.txt")) {
            log.info("read file complete {}", fileStream);

            //创建使用的ByteBuffer
            ByteBuffer byteBuffer = ByteBuffer.allocate(100);
            log.info("init buffer complete {}", byteBuffer);

            //获取管道
            FileChannel channel = fileStream.getChannel();
            channel.read(byteBuffer);
            log.info("channel read complete {}", channel);

            //channel将数据写进buffer
            while (byteBuffer.remaining() > 0) {
                byte b = byteBuffer.get();
                System.out.println(b);
            }


            //use buffer,reset limit=currPosition and position=0,翻转等于重置参数的开始
            byteBuffer.flip();
            log.info("flip complete , byteBuffer is {}", byteBuffer);

            //这边是重置成初始的状态
            byteBuffer.clear();
            log.info("clear complete");
        }

    }

}
